<template>
  <div class="login-container">
    <div class="login-card">
      <h2 class="login-title">用户登录</h2>
      <form @submit.prevent="handleLogin" class="login-form">
        <!-- 用户名输入 -->
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            id="username"
            v-model="loginForm.username"
            type="text"
            placeholder="请输入用户名"
            required
            :disabled="loading"
          />
        </div>

        <!-- 密码输入 -->
        <div class="form-group">
          <label for="password">密码</label>
          <input
            id="password"
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            required
            :disabled="loading"
          />
        </div>

        <!-- 记住我 -->
        <div class="form-options">
          <label class="checkbox-label">
            <input
              type="checkbox"
              v-model="loginForm.rememberMe"
              :disabled="loading"
            />
            <span class="checkmark"></span>
            记住我
          </label>
          <a href="#" class="forgot-password">忘记密码？</a>
        </div>

        <!-- 登录按钮 -->
        <button
          type="submit"
          :disabled="loading"
          class="login-btn"
        >
          {{ loading ? '登录中...' : '登录' }}
        </button>

        <!-- 注册链接 -->
        <div class="register-link">
          还没有账号？<a href="#" @click="$emit('switchToRegister')">立即注册</a>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { userApi } from '../api/index.js'

export default {
  name: 'UserLogin',
  emits: ['switchToRegister', 'loginSuccess'],
  setup(props, { emit }) {
    const loading = ref(false)
    
    const loginForm = reactive({
      username: '',
      password: '',
      rememberMe: false
    })

    // 组件挂载时从localStorage恢复记住的用户信息
    onMounted(() => {
      const rememberedUsername = localStorage.getItem('rememberedUsername')
      if (rememberedUsername) {
        loginForm.username = rememberedUsername
        loginForm.rememberMe = true
      }
    })

    // 处理登录
    const handleLogin = async () => {
      if (!loginForm.username || !loginForm.password) {
        alert('请输入用户名和密码')
        return
      }

      // 防重复提交：如果正在登录中，直接返回
      if (loading.value) {
        console.log('正在登录中，忽略重复请求')
        return
      }

      // 检查是否已经登录
      const existingToken = localStorage.getItem('token')
      if (existingToken) {
        alert('您已经登录，请勿重复登录')
        return
      }

      try {
        loading.value = true
        
        // 构造用户对象，根据后端API文档要求
        const user = {
          username: loginForm.username,
          password: loginForm.password
        }

        const result = await userApi.login(user)
        
        // 处理记住我功能
        if (loginForm.rememberMe) {
          localStorage.setItem('rememberedUsername', loginForm.username)
        } else {
          localStorage.removeItem('rememberedUsername')
        }

        // 保存token到localStorage
        console.log('登录响应原始数据:', result)
        console.log('登录响应类型:', typeof result)
        
        let token = null
        
        // 如果响应直接是字符串，那就是token
        if (typeof result === 'string') {
          token = result
        } 
        // 如果是对象，尝试从各种可能的字段获取token
        else if (result && typeof result === 'object') {
          console.log('登录响应的所有属性:', Object.keys(result))
          token = result.token || result.data?.token || result.access_token || result.accessToken
        }
        
        console.log('提取到的token:', token)
        
        if (token) {
          localStorage.setItem('token', token)
          console.log('Token已保存到localStorage:', token)
        } else {
          console.error('登录响应中没有找到token，完整响应:', JSON.stringify(result, null, 2))
        }

        alert('登录成功！')
        emit('loginSuccess', result)
        
        // 清空密码字段
        loginForm.password = ''
      } catch (error) {
        console.error('登录失败:', error)
        alert(error.message || '登录失败')
      } finally {
        loading.value = false
      }
    }

    return {
      loginForm,
      loading,
      handleLogin
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 400px;
}

.login-title {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
  font-size: 28px;
  font-weight: 600;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 500;
  color: #555;
  font-size: 14px;
}

.form-group input {
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s ease;
}

.form-group input:focus {
  outline: none;
  border-color: #667eea;
}

.form-group input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px 0;
}

.checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
  color: #666;
}

.checkbox-label input[type="checkbox"] {
  display: none;
}

.checkmark {
  width: 18px;
  height: 18px;
  border: 2px solid #ddd;
  border-radius: 4px;
  margin-right: 8px;
  position: relative;
  transition: all 0.3s ease;
}

.checkbox-label input[type="checkbox"]:checked + .checkmark {
  background-color: #667eea;
  border-color: #667eea;
}

.checkbox-label input[type="checkbox"]:checked + .checkmark::after {
  content: '';
  position: absolute;
  left: 5px;
  top: 2px;
  width: 4px;
  height: 8px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.forgot-password {
  color: #667eea;
  text-decoration: none;
  font-size: 14px;
}

.forgot-password:hover {
  text-decoration: underline;
}

.login-btn {
  padding: 14px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: transform 0.2s ease;
  margin-top: 10px;
}

.login-btn:hover:not(:disabled) {
  transform: translateY(-2px);
}

.login-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.register-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.register-link a {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
}

.register-link a:hover {
  text-decoration: underline;
}

@media (max-width: 480px) {
  .login-card {
    padding: 30px 20px;
  }
  
  .form-options {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
}
</style>